package com.ruoyi.web.controller.module.titleMenu;

import java.util.List;
import java.util.Arrays;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.system.domain.module.*;
import com.ruoyi.system.domain.module.mer.Mer;
import com.ruoyi.system.domain.module.product.MallGroupProduct;
import com.ruoyi.system.domain.module.product.Product;
import com.ruoyi.system.domain.module.titleMenu.TitleMenuSectionLinks;
import com.ruoyi.system.service.module.*;
import com.ruoyi.system.service.module.mer.IMerService;
import com.ruoyi.system.service.module.product.IMallGroupProductService;
import com.ruoyi.system.service.module.product.IProductService;
import com.ruoyi.system.service.module.titleMenu.ITitleMenuSectionLinksService;
import com.ruoyi.system.service.system.ISysDictDataService;
import lombok.RequiredArgsConstructor;
import javax.validation.constraints.*;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.validate.AddGroup;
import com.ruoyi.common.core.validate.EditGroup;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.core.page.TableDataInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 每个内容行里的数据Controller
 *
 * @author ruoyi
 * @date 2021-08-11
 */
@Validated
@Api(value = "每个内容行里的数据控制器", tags = {"每个内容行里的数据管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/module/titleMenu/section/links")
public class TitleMenuSectionLinksController extends BaseController {

    private final ITitleMenuSectionLinksService titleMenuSectionLinksService;
    private final IProductService productService;
    private final ISysDictDataService sysDictDataService;
    private final IAdBannerService adBannerService;
	private final ICouponsService couponsService;
	private final IMerService merService;
	private final IMallGroupProductService groupProductService;

	@Value("${ruoyi.imgUrl}")
	private String imgUrl;

//	@Value("${ruoyi.imgUrlOss}")
//	private String imgUrlOss;

    /**
     * 查询每个内容行里的数据列表
     */
    @ApiOperation("查询每个内容行里的数据列表")
    @PreAuthorize("@ss.hasPermi('module:sectionlinks:list')")
    @GetMapping("/list")
    public TableDataInfo<TitleMenuSectionLinks> list(@Validated TitleMenuSectionLinks titleMenuSectionLinks) {
        QueryWrapper<TitleMenuSectionLinks> qw = new QueryWrapper<>();
        if(titleMenuSectionLinks.getSectionId()!=null){
            qw.eq("section_id",titleMenuSectionLinks.getSectionId());
        }
        qw.orderByAsc("sort");
        TableDataInfo<TitleMenuSectionLinks> td = PageUtils.buildDataInfo(titleMenuSectionLinksService.page(PageUtils.buildPage(),qw));
        List<TitleMenuSectionLinks> list = td.getRows();
        if(CollUtil.isNotEmpty(list)){
            list.forEach(link -> {
                if(StrUtil.isNotEmpty(link.getImgUrl())){
                    if(StrUtil.isNotEmpty(link.getImgUrl()) && link.getImgUrl().indexOf("http") < 0){
                        link.setImgUrlPath(imgUrl + link.getImgUrl());
                    }else{
                        link.setImgUrlPath(link.getImgUrl());
                    }
                }else{
                    link.setImgUrlPath("");
                }

				if(StrUtil.isNotEmpty(link.getIconUrl())){
					if(StrUtil.isNotEmpty(link.getIconUrl()) && link.getIconUrl().indexOf("http") < 0){
						link.setIconUrlPath(imgUrl + link.getIconUrl());
					}else{
						link.setIconUrlPath(link.getIconUrl());
					}
				}else{
					link.setIconUrlPath("");
				}

				SysDictData dictData = sysDictDataService.selectDictData("link_type",link.getLinkType());
				if(dictData!=null){
					link.setLinkTypeName(dictData.getDictLabel());
				}
                if(link.getLinkType().equals("product")){
					if(link.getLinkId()!=null){
						Product product = productService.goodsDetail(Long.parseLong(link.getLinkId().toString()));
						if(product!=null){
							Mer mer = merService.getById(product.getMerId());
							if(mer!=null){
								product.setMerName(mer.getShopName());
							}

							if(StrUtil.isEmpty(link.getImgUrl())){
								link.setImgUrlPath(imgUrl + product.getImage());
							}
						}
						link.setProduct(product);
					}
				} else if(link.getLinkType().equals("group")){
					if(link.getLinkId()!=null){
						MallGroupProduct groupProduct = groupProductService.findById(link.getLinkId());
						if(groupProduct!=null){
							Product product = productService.goodsDetail(groupProduct.getLinkId());
							if(StrUtil.isEmpty(link.getImgUrl())){
								link.setImgUrlPath(imgUrl + product.getImage());
							}
							link.setProduct(product);
						}
					}
				} else if(link.getLinkType().equals("coupons")){
					if(link.getLinkId()!=null){
						Coupons coupons = couponsService.findById(link.getLinkId());
						if(coupons!=null){
							if(StrUtil.isNotEmpty(coupons.getImgUrl())){
								link.setImgUrlPath(imgUrl + coupons.getImgUrl());
							}
						}
						link.setCoupons(coupons);
					}
				}
            });
        }
        return td;
    }

    /**
     * 获取每个内容行里的数据详细信息
     */
    @ApiOperation("获取每个内容行里的数据详细信息")
    @PreAuthorize("@ss.hasPermi('module:sectionlinks:query')")
    @GetMapping("/{id}")
    public AjaxResult<TitleMenuSectionLinks> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        TitleMenuSectionLinks sectionLinks = titleMenuSectionLinksService.getById(id);
        if(sectionLinks != null){

			if(StrUtil.isNotEmpty(sectionLinks.getImgUrl())){
				if(StrUtil.isNotEmpty(sectionLinks.getImgUrl()) && sectionLinks.getImgUrl().indexOf("http") < 0){
					sectionLinks.setImgUrlPath(imgUrl + sectionLinks.getImgUrl());
				}else{
					sectionLinks.setImgUrlPath(sectionLinks.getImgUrl());
				}
			}else{
				sectionLinks.setImgUrlPath("");
			}

            if(sectionLinks.getLinkType().equals("product")){
                Product product = productService.goodsDetail(Long.parseLong(sectionLinks.getLinkId()+""));
                if(product!=null){
					Mer mer = merService.getById(product.getMerId());
					if(mer!=null){
						product.setMerName(mer.getShopName());
					}
				}
                sectionLinks.setProduct(product);
            }else if(sectionLinks.getLinkType().equals("advert")){
                AdBanner banner = adBannerService.findById(sectionLinks.getLinkId());
                if(banner!=null){
                    if(banner.getAdType() != null){
                        banner.setAdTypeName(sysDictDataService.selectDictLabel("banner_type",banner.getAdType().toString()));
                    }

                    if(StrUtil.isNotEmpty(banner.getImgUrl())){
                        banner.setImgPath(imgUrl + banner.getImgUrl());
                    }

                    if(StrUtil.isNotEmpty(banner.getLinkType())){
                        banner.setLinkTypeName(sysDictDataService.selectDictLabel("link_type",banner.getLinkType()));
                    }
                }
                sectionLinks.setBanner(banner);
            }
        }
        return AjaxResult.success(sectionLinks);
    }

    /**
     * 新增每个内容行里的数据
     */
    @ApiOperation("新增每个内容行里的数据")
    @PreAuthorize("@ss.hasPermi('module:sectionlinks:add')")
    @Log(title = "每个内容行里的数据", businessType = BusinessType.INSERT)
    @RepeatSubmit
    @PostMapping()
    public AjaxResult<Void> add(@Validated(AddGroup.class) @RequestBody TitleMenuSectionLinks titleMenuSectionLinks) {
        return toAjax(titleMenuSectionLinksService.save(titleMenuSectionLinks) ? 1 : 0);
    }

    /**
     * 修改每个内容行里的数据
     */
    @ApiOperation("修改每个内容行里的数据")
    @PreAuthorize("@ss.hasPermi('module:sectionlinks:edit')")
    @Log(title = "每个内容行里的数据", businessType = BusinessType.UPDATE)
    @RepeatSubmit
    @PutMapping()
    public AjaxResult<Void> edit(@Validated(EditGroup.class) @RequestBody TitleMenuSectionLinks titleMenuSectionLinks) {
        return toAjax(titleMenuSectionLinksService.updateById(titleMenuSectionLinks) ? 1 : 0);
    }

    /**
     * 删除每个内容行里的数据
     */
    @ApiOperation("删除每个内容行里的数据")
    @PreAuthorize("@ss.hasPermi('module:sectionlinks:remove')")
    @Log(title = "每个内容行里的数据" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult<Void> remove(@NotEmpty(message = "主键不能为空") @PathVariable Long[] ids) {
        return toAjax(titleMenuSectionLinksService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }
}
